package com.letv.whatslive.web.util.util;

import com.letv.whatslive.common.utils.ObjectUtils;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 音频格式转换工具类
 * Created by wangjian7 on 2016/2/26.
 */
public class JaveUtils {

    private static final Logger logger = LoggerFactory.getLogger(JaveUtils.class);

    /**
     *
     * @param sourceFilePath 源文件路径
     * @param deleteSourceFile 是否删除源文件
     * @return desFilePath 目标文件路径
     * @throws Exception
     */
    public static String decodeAudioToAmr(String sourceFilePath, boolean deleteSourceFile) throws Exception {
        AudioAttributes audio = new AudioAttributes();
        if(isWinOperateSystem()){
            audio.setCodec("libamr_nb");
        }else{
            //linux使用libopencore开源库转换成amr
            audio.setCodec("libopencore_amrnb");
        }
        audio.setBitRate(new Integer(12200)); //AMR 12.2 - Encodes at 12.2kbit/s
        audio.setChannels(new Integer(1));
        audio.setSamplingRate(new Integer(8000));
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("amr");
        attrs.setAudioAttributes(audio);
        Encoder encoder = new Encoder();
        File sourceFile = new File(sourceFilePath);
        String desFilePath = sourceFilePath.split("\\.")[0]+".amr";
        File destFile = new File(desFilePath);
        try {
            encoder.encode(sourceFile, destFile, attrs);
        } catch (EncoderException e) {
            if(e.getMessage().contains("muxing overhead")){
                logger.warn(e.getMessage());
            }else{
                throw new Exception("decode audio to amr error", e);
            }

        }
        if(deleteSourceFile){
            sourceFile.delete();
        }
        return desFilePath;
    }

    /**
     * 获取音频的秒数整数
     * @param secends
     * @return
     */
    public static Integer getAudioSecends(String secends){
        return  ObjectUtils.toDouble(secends).intValue()+1;
    }

    /**
     * 根据文件路径将文件读取到byte数组
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] getVoiceBytes(String filePath) throws Exception {
        byte[] result = null;
        ByteArrayOutputStream out_arr = new ByteArrayOutputStream();
        File voiceFile = new File(filePath);
        try {
            FileInputStream in_file = new FileInputStream(voiceFile);
            int index = 0;
            byte[] buffer = new byte[512];
            while ((index = in_file.read(buffer, 0, 512)) != -1) {
                out_arr.write(buffer, 0, index);
            }
            in_file.close();
            result = out_arr.toByteArray();
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                out_arr.close();
            } catch (IOException e) {
                throw e;
            }
        }
        return result;
    }

    /**
     * 判断是不是windows操作系统
     * @return
     */
    private static boolean isWinOperateSystem(){
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if(os.startsWith("win") || os.startsWith("Win")){
            return true;
        }else{
            return false;
        }
    }
}
